<template>
  <div class="nbtable">
    <fc-title title="决策表因子">
      <Feature
        @Listchange="onFeatureUpdate"
        @addFeature="(value) => addFeatures(value)"
        :selectedItems="selectedItems"
        :type="type"
      />
    </fc-title>
    <br />
    <fc-title title="决策表">
      <a-table
        class="ellipsis-header"
        :columns="hhead"
        :data-source="hdata"
        :pagination="false"
        bordered
        :scroll="{ y: 400 }"
      >
        <template slot="name" slot-scope="text, record, scope, columnDef">
          <editable-cell
            :text="text"
            :editStatus="editStatus"
            @change="onCellChange(record.key, scope, $event, text, columnDef)"
          />
        </template>
        <!-- <template slot="operation" slot-scope="text,record">
          <a-button type="link" @click="deleteRow(record)">删除</a-button>
        </template>-->
      </a-table>
    </fc-title>

    <a-modal v-model="addFeatureVisible" title="添加因子" :closable="true" @ok="handleOk">
      <!-- <a-button @click="getAllFeatures">查询</a-button> -->
      <a-table
        :columns="featureColumn"
        :data-source="featureData"
        rowKey="featureCode"
        :pagination="false"
        :row-selection="{
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange,
          getCheckboxProps,
        }"
      ></a-table>
    </a-modal>
  </div>
</template>
<script>
import EditableCell from './EditableCell'
import FeatureItem from './FeatureItem'
import FeatureCombine from './FeatureCombine'
import DmtValue from './DmtValue'
import FcTitle from './FcTitle'
import Feature from './Feature'
// import { getDmtModel, downloadTemplate, saveDmtModel, loadDmtModel, getFeatures } from '@/api/dmt'

const installColumnRender = (columDef) => {
  if (columDef.children != null && columDef.children.length > 0) {
    columDef.children.forEach((v) => {
      installColumnRender(v)
    })
  } else {
    columDef.scopedSlots = { customRender: 'name' }
  }
}

const featureColumn = [
  {
    title: 'Id',
    dataIndex: 'id',
    key: 'id',
  },
  {
    title: '因子代码',
    dataIndex: 'featureCode',
    key: 'featureCode',
  },
  {
    title: '因子名称',
    dataIndex: 'featureName',
    key: 'featureName',
  },
  {
    title: '因子描述',
    dataIndex: 'desc',
    key: 'desc',
  },
]

import data from './data.json'
// import { find } from 'store/storages/all'
import { getFactorList, getFactorWithCode } from './api/ruleApi'
import { matchingTypeLabel } from './model/RuleFactorValue'

/**
 * 这里的2是当前这一列的分区大小
 * @param {*} value
 * @param {*} row
 * @param {*} index
 * @returns
 */
export default {
  components: {
    EditableCell,
    FeatureItem,
    FeatureCombine,
    DmtValue,
    FcTitle,
    Feature,
  },
  created() {
    this.form = this.$form.createForm(this)
    this.featureData = getFactorList().map((item, index) => ({
      ...item,
      id: String(index + 1),
      featureCode: item.code,
      featureName: item.label,
    }))
  },
  computed: {
    uploadUrl: function() {
      const upload = 'http://localhost:4000/api/dmt/model/upload/' + this.model.code
      return upload
    },
  },
  data() {
    return {
      matchingTypeLabel,
      createLoading: false,
      editStatus: false,
      dmtName: 'aaa',
      mem: 'ss',
      hhead: [],
      hdata: [],
      rowClassName: 'rowClassName',
      model: {},

      selectedKeys: [],
      filteredItems: [],
      disabled: false,

      addFeatureVisible: false,
      featureColumn: featureColumn,
      featureData: [],

      type: '',

      selectedRowKeys: [],
      selectedFeatures: [],

      selectedItems: [],

      param: {},

      dmtValues: [],
    }
  },
  computed: {
    customHeaderRow(record) {
      return {
        class: 'mclass',
        on: {
          click: (row) => {
            console.log('====')
          },
        },
      }
    },
  },
  methods: {
    test() {
      console.log('data=====', this.hdata)
    },

    onValueUpdate: function(values) {
      console.log('返回值模型数据:', values)
      this.dmtValues = values
    },

    // 去除因子名称，递归
    removeFeatureName: function(feature) {
      feature.forEach((item) => {
        if (item.children) {
          this.removeFeatureName(item.children)
        } else {
          item.title = item.title.split('/').pop()
        }
      })
    },
    // 生成行
    generateColumns(arrays, depth = 0, pre) {
      if (arrays.length === 0) {
        return [
          {
            title: '结果集',
            dataIndex: 'result',
            key: 'result',
            align: 'center',
            scopedSlots: { customRender: 'name' },
          },
        ]
      }
      if (depth >= arrays.length) {
        return []
      }
      const arr = getFactorWithCode(arrays[depth])
      return arr?.values.map((item) => {
        console.log('----', item, this.matchingTypeLabel)
        let title = `${item.label}(${this.matchingTypeLabel[item.matchingRule]})`
        let dataIndex = pre ? `${pre}_${item.code}` : `${item.code}`
        const children = this.generateColumns(arrays, depth + 1, dataIndex)

        if (children.length > 0) {
          return { title, children }
        }
        return {
          title,
          ellipsis: true,
          align: 'center',
          dataIndex,
          scopedSlots: { customRender: 'name' },
        }
      })
    },

    //正交生成列
    cartesianProduct(arr, index = 0, current = {}) {
      // 结果数组
      let result = []

      // 如果索引等于数组的长度，意味着已经处理完所有数组
      if (index === arr.length) {
        return [current]
      }

      // 遍历当前层级的数组
      arr[index].forEach((obj) => {
        // 对于数组中的每个对象，获取键和值
        const key = Object.keys(obj)[0]
        const value = obj[key]
        // 创建一个新的对象，包含之前的结果和当前的键值对
        const newCurrent = {
          ...current,
          [key]: `${value.label}(${this.matchingTypeLabel[value.matchingRule]})`,
          id: `ccn_${Math.random() * 100}`,
        }

        // 递归调用，处理下一个数组
        const nextResult = this.cartesianProduct(arr, index + 1, newCurrent)

        // 将结果合并到最终结果数组中
        result = result.concat(nextResult)
      })

      return result
    },

    /**
     * 自定义的列表头渲染器
     */

    getCheckboxProps(record) {
      if (this.type === 'row') {
        return {
          props: {
            ...record,
            disabled: !!this.param.rowFeature?.find((item) => item.id === record.featureCode), // Column configuration not to be checked
          },
        }
      } else {
        return {
          props: {
            ...record,
            disabled: !!this.param.colFeature?.find((item) => item.id === record.featureCode), // Column configuration not to be checked
          },
        }
      }
    },

    generateDmt() {
      this.hdata = []
      this.hhead = []
      console.log('pram', this.param)
      // let colValue = this.param.colFeature.map(item => item.values.map(item => item.label))
      let colValue = this.param.colFeature.map((item) => item.id)

      let rowValue = this.param.rowFeature.map((item) => {
        const key = item.id
        return item.values.map((item) => ({ [key]: item }))
      })

      if (!colValue.length && !rowValue.length) return

      colValue = !colValue.length && rowValue.length ? [] : colValue
      console.log('rowValue', colValue, rowValue)

      const rowId = this.param.rowFeature.map((item) => item.id)
      const rowName = this.param.rowFeature.map((item) => ({ [item.id]: item.name })).reverse()

      const hhead = this.generateColumns(colValue)
      this.hhead = hhead ?? []
      console.log('hhead', hhead)
      let data1 = this.cartesianProduct(rowValue)
      // data1.forEach(item => {
      //   const fatorKeys = Object.keys(item)
      //   fatorKeys.forEach(key => {
      //     const fator = getFactorWithCode(key)
      //     if (fator) {
      //       fatorKeys[key] = `${fatorKeys[key]}(${this.matchingTypeLabel(fator.data)})`
      //     }
      //   })
      // })
      console.log('data1', data1)
      rowName.forEach((item) => {
        // 在数组第一行添加
        this.hhead.unshift({
          title: Object.values(item)[0],
          dataIndex: Object.keys(item)[0],
          key: Object.keys(item)[0],
          ellipsis: true,
          width: 120,
          align: 'center',
          // fixed: 'left',
          customRender: (value, record, index) => {
            const splitValue = value.split('(')[0]
            const findIndex = rowId.findIndex((item) => getFactorWithCode(item).values.find((item) => item.label === splitValue))
            let key = '',
              rowLen = 1
            if (findIndex + 1 < rowId.length) {
              key = rowId.filter((_, index) => index > findIndex)
            }
            if (key) {
              key.forEach((item) => {
                const datas = getFactorWithCode(item).values
                const len = datas.length
                rowLen = rowLen * len
              })
            }
            if (find && index % rowLen === 0) {
              return {
                children: value,
                attrs: {
                  rowSpan: rowLen,
                },
                style: {
                  color: '#A00',
                },
              }
            } else {
              return {
                children: value,
                attrs: {
                  rowSpan: 0,
                },
                style: {
                  color: '#A00',
                },
              }
            }
          },
        })
      })
      // this.hhead.push({
      //   title: '操作',
      //   dataIndex: 'operation',
      //   key: 'operation',
      //   fixed: 'right',
      //   align: 'center',
      //   width: 100,
      //   scopedSlots: { customRender: 'operation' }
      // })
      this.hdata = data1
      console.log('hhead:', this.hhead)
    },

    // 删除表格数据
    deleteRow(record) {
      console.log('record:', record)
      this.hdata = this.hdata.filter((item) => item.id !== record.id)
      console.log('this.hdata:', this.hdata)
      if (!this.hdata.length) {
        this.type = 'clear'
      }
    },

    // 跟新因子
    onFeatureUpdate: function(param) {
      param.name = ''
      console.log('因子组合发生变化:', param)
      this.param = param
      this.generateDmt()
    },

    getAllFeatures: function() {
      this.featureData = getFactorList().map((item, index) => ({
        ...item,
        id: String(index + 1),
        featureCode: item.code,
        featureName: item.label,
      }))
    },

    onSelectChange(selected) {
      console.log('selectedRowKeys changed:', selected)
      this.selectedRowKeys = selected
    },

    addFeatures(value) {
      this.addFeature(value)
    },

    addFeature: function(value) {
      this.addFeatureVisible = true
      this.getAllFeatures()
      this.type = value
      if (Object.keys(this.param).length === 0) return
      console.log('proar', this.type, this.param)
      if (value === 'row') {
        this.selectedRowKeys = Array.from(new Set([...this.param.rowFeature.map((item) => item.id), ...this.param.colFeature.map((item) => item.id)]))
        console.log('====', this.selectedRowKeys)
      } else {
        this.selectedRowKeys = Array.from(new Set([...this.param.colFeature.map((item) => item.id), ...this.param.rowFeature.map((item) => item.id)]))
        console.log('====', this.selectedRowKeys)
      }
    },
    handleOk: function(e) {
      this.addFeatureVisible = false
      this.selectedFeatures = []
      console.log('selectedRowKeys', this.selectedRowKeys, this.type, this.param)
      this.selectedRowKeys.forEach((v) => {
        let value = this.featureData.find((item) => item.featureCode === v)
        if (this.type === 'row' && !this.param.rowFeature?.find((e) => e.id === v)) {
          this.selectedFeatures.push(value)
        } else if (this.type === 'col' && !this.param.colFeature?.find((e) => e.id === v)) {
          this.selectedFeatures.push(value)
        } else if (Object.keys(this.param).length === 0) {
          this.selectedFeatures.push(value)
        }
      })
      console.log('++++', getFactorWithCode('A1004'))
      this.selectedItems = this.selectedFeatures.map((v) => {
        return {
          id: v.featureCode,
          name: v.featureName,
          values: v.values,
        }
      })

      console.log('选中的因子:', this.selectedFeatures)
    },
    handleDisable(disabled) {
      this.disabled = disabled
    },
    /**
     * 决策表上编辑的值更新到模型上.
     */
    onCellChange: function(index, rowIndex, newValue, oldValue, columnDef) {
      console.log('====', index, rowIndex, newValue, oldValue, columnDef)
      const column = columnDef.dataIndex
      this.hdata[rowIndex][column] = newValue
    },

    handleChange: function() {
      console.log('handle change happend.')
    },

    loadModelData: function() {
      this.hdata = []
      this.hhead = []

      const code = this.model.code
      if (!code) {
        return
      }

      loadDmtModel(code).then((response) => {
        const data = response.model
        const meta = response.meta
        const head = response.head

        this.model = response

        this.hdata = data
        this.hdata.forEach((record) => {
          record.meta = meta
        })

        head.forEach((h) => {
          if (h.cardinal) {
            h.customRender = this.columnHeadRender
          } else {
            installColumnRender(h)
          }
        })

        this.hhead = head
      })
    },

    /**
     * 这样做的性能是有问题的，需要重构优化
     */
    saveModelData: function() {
      if (this.hdata.length === 0) {
        return
      }

      const strData = JSON.stringify(this.model)

      const deepCopy = JSON.parse(strData)

      deepCopy.model.forEach((v) => {
        delete v['meta']
      })

      saveDmtModel(deepCopy).then((response) => {
        if (!this.model.mode) {
          this.model.code = response.code

          const h = this.$createElement
          this.$info({
            title: '提示消息',
            content: h('div', {}, [h('p', '模型保存成功.')]),
            onOk() {},
          })
        }
      })
    },

    downloadTemplate: function() {
      this.editStatus = !this.editStatus
    },
    compont() {
      this.editStatus = false
    },

    // getDynamicModel: function () {
    //   const param = this.buildModel()

    //   if (!param) {
    //     return
    //   }

    //   this.hdata = []
    //   this.hhead = []

    //   getDmtModel(param).then(response => {
    //     const data = response.model
    //     const meta = response.meta
    //     const head = response.head

    //     this.model = response

    //     this.hdata = data
    //     this.hdata.forEach(record => {
    //       record.meta = meta
    //     })

    //     head.forEach(h => {
    //       if (h.cardinal) {
    //         h.customRender = this.columnHeadRender
    //       } else {
    //         installColumnRender(h)
    //       }
    //     })

    //     this.hhead = head
    //   })
    // }
  },
  mounted() {},
}
</script>

<style scoped>
/** 这里的这时的颜色样式为什么会不生效，字体可以生效。 */
.mclass {
  color: blue;
  background-color: blueviolet;
}

::v-deep .ant-table-thead > tr > th,
::v-deep .ant-table-tbody > tr > td {
  padding: 5px 5px;
}

::v-deep .ant-table-row-hover > td {
  background-color: red;
  color: green;
}

/* 实现样式穿透 */
::v-deep .ant-table-tbody > tr.ant-table-row:hover > td {
  background: none !important;
}
::v-deep .ant-table-align-center {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
